<template>
    <view class="comm-list-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header title="农资入库"></page-header>
        <view class="search-box1">
            <uni-search-bar
                placeholder="搜索农资入库记录"
                v-model="searchKeyword"
                @confirm="handleSearch"
                @input="handleSearch"
                :radius="100"
                cancelButton="none" />
        </view>
        <!-- 筛选组件 -->
        <warehouse-filter ref="warehouseFilter" @filter-change="handleFilterChange" />
        <view class="warehouse-list">
            <view class="title">入库记录</view>

            <view
                class="warehouse-item"
                v-for="(item, index) in filteredWarehouseList"
                :key="index">
                <!-- 头部信息 -->
                <view class="item-header">
                    <view class="header-left">
                        <text class="item-title">
                            {{ item.agriculturalType }}
                        </text>
                    </view>
                    <!-- <view class="item-tag">化肥</view> -->
                </view>

                <!-- 详细信息 -->
                <view class="item-details">
                    <view class="detail-row">
                        <text class="detail-label">入库时间：</text>
                        <text class="detail-value">{{ formatDate(item.inDate) }}</text>
                    </view>

                    <view class="detail-row">
                        <text class="detail-label">仓库名称：</text>
                        <text class="detail-value">{{ item.warehouseName }}</text>
                    </view>

                    <view class="detail-row">
                        <text class="detail-label">仓库位置：</text>
                        <text class="detail-value">{{ item.warehouseLocation }}</text>
                    </view>

                    <view class="detail-row">
                        <text class="detail-label">规格：</text>
                        <text class="detail-value">{{ item.specification }}</text>
                    </view>

                    <view class="detail-row">
                        <text class="detail-label">数量：</text>
                        <text class="detail-value">{{ item.quantity }}</text>
                    </view>

                    <view class="detail-row">
                        <text class="detail-label">来源：</text>
                        <text class="detail-value">{{ item.procurementMethod }}</text>
                    </view>

                    <view class="detail-row">
                        <text class="detail-label">厂商：</text>
                        <text class="detail-value">{{ item.manufacturer }}</text>
                    </view>

                    <view class="detail-row">
                        <text class="detail-label">备注：</text>
                        <text class="detail-value">{{ item.remark }}</text>
                    </view>
                </view>

                <!-- 展示图片 -->
                <view class="item-images" v-if="item.images">
                    <image
                        v-for="(img, imgIndex) in formatImages(item.images).slice(0, 2)"
                        :key="imgIndex"
                        :src="img"
                        mode="aspectFit"></image>
                </view>
            </view>

            <!-- 加载更多提示 -->
            <view class="load-more-container" v-if="filteredWarehouseList.length > 0">
                <view v-if="loadingMore" class="loading-more">
                    <text class="loading-text">加载中...</text>
                </view>
                <view v-else-if="!hasMore" class="no-more">
                    <text class="no-more-text">没有更多数据了</text>
                </view>
            </view>
        </view>
        <!-- 无数据提示 -->
        <empty-data v-if="filteredWarehouseList.length === 0 && !loading" />

        <view class="add-button" @click="navigateTo('/pages/warehouse/warehouseIn/addWarehouseIn')">
            <text class="add-icon" style="font-size: 28rpx">新增入库</text>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import EmptyData from '@/components/EmptyData/index.vue'
import WarehouseFilter from '@/components/WarehouseFilter/index.vue'
// 导入格式化函数
import { formatDateChinese, formatImages } from '@/utils/util.js'
import { mapGetters, mapActions } from 'vuex'
// 导入API
import { warehouse } from '@/utils/api/index.js'

export default {
    components: {
        PageHeader,
        EmptyData,
        WarehouseFilter,
    },
    data() {
        return {
            title: '农资入库',
            searchKeyword: '',
            warehouseList: [],
            loading: false,
            loadingMore: false,
            hasMore: true,
            pageParams: {
                pageNo: 1,
                pageSize: 30,
            },
        }
    },
    computed: {
        ...mapGetters({
            getDictByType: 'getDictByType',
            getDictLabel: 'getDictLabel',
            getWarehouseNameById: 'getWarehouseNameById',
            getLocationNameById: 'getLocationNameById',
        }),
        filteredWarehouseList() {
            return this.warehouseList
        },
    },
    async onLoad() {
        // 加载仓库数据
        await this.fetchWarehouseData()
    },
    onShow() {
        this.fetchWarehouseList()
    },
    // 下拉刷新
    onPullDownRefresh() {
        this.fetchWarehouseList()
    },
    // 触底加载更多
    onReachBottom() {
        this.loadMoreData()
    },
    methods: {
        ...mapActions(['getDictByType', 'fetchWarehouseData']),

        // 获取农业资源类型的显示文本
        getAgriculturalTypeLabel(materialId,locationId) {
            if (!materialId) return '未知类型' // 默认值

            // 先尝试从 category 字典获取主类型
            const categoryLabel = this.getDictLabel(locationId, materialId)
            if (categoryLabel && categoryLabel !== materialId) {
                return categoryLabel
            }
            // 如果都没有找到，返回原始值
            return materialId
        },

        // 统一处理筛选变化
        handleFilterChange(filterData) {
            console.log('统一处理筛选变化')
            console.log(filterData)
            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 清除之前的筛选条件
            delete this.pageParams.startDate
            delete this.pageParams.endDate
            delete this.pageParams.materialId

            // 时间筛选
            if (filterData.startDate && filterData.endDate) {
                this.pageParams.startDate = filterData.startDate
                this.pageParams.endDate = filterData.endDate
            }

            // 农业资类型筛选
            if (filterData.typeId) {
                this.pageParams.materialId = filterData.typeId
            }

            // 重新请求接口
            this.fetchWarehouseList()
        },

        // 处理搜索变化
        handleSearch(e) {
            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 更新关键词搜索参数
            if (this.searchKeyword) {
                this.pageParams.keyword = e || this.searchKeyword
            } else {
                delete this.pageParams.keyword
            }

            // 重新请求接口
            this.fetchWarehouseList()
        },

        async fetchWarehouseList(isLoadMore = false) {
            
            try {
                if (isLoadMore) {
                    this.loadingMore = true
                } else {
                    this.loading = true
                    uni.showLoading({ title: '加载中...' })
                }

                // 调用真实的API
                const res = await warehouse.getWarehouseInPage(this.pageParams)

                if (res.code === 0) {
                    // 处理接口返回的数据，将接口字段映射到页面显示字段
                    const newList = res.data.list.map((item) => ({
                        id: item.inId,
                        inDate: item.inTime,
                        agriculturalType: this.getAgriculturalTypeLabel(item.materialId,item.locationId),
                        warehouseName: this.getWarehouseNameById(item.warehouseId),
                        warehouseLocation: this.getDictLabel('category', item.locationId),
                        specification: this.getDictLabel('spec_unit', item.specId),
                        quantity: item.quantity,
                        unit: '袋', // 默认单位
                        source: item.supplier || '未知来源',
                        manufacturer: item.supplier || '未知厂商',
                        procurementMethod:
                            this.getDictLabel('procurement_method', item.procurementMethod) ||
                            '未知来源',
                        remark: item.remark || '',
                        images: item.images || '',
                        // 保留原始数据用于编辑
                        originalData: item,
                    }))

                    if (isLoadMore) {
                        // 加载更多时追加数据
                        this.warehouseList = [...this.warehouseList, ...newList]
                    } else {
                        // 首次加载或刷新时替换数据
                        this.warehouseList = newList
                    }

                    // 判断是否还有更多数据
                    this.hasMore = newList.length >= this.pageParams.pageSize
                } else {
                    throw new Error(res.msg || '获取数据失败')
                }
            } catch (error) {
                console.error('获取农资入库记录失败:', error)
                if (!isLoadMore) {
                    uni.showToast({
                        title: '获取数据失败',
                        icon: 'none',
                    })
                    // 使用默认数据
                    this.warehouseList = this.getDefaultData()
                }
            } finally {
                this.loading = false
                this.loadingMore = false
                uni.hideLoading()
                uni.stopPullDownRefresh()
            }
        },

        // 获取默认数据，在API请求失败时使用
        getDefaultData() {
            return []
        },

        navigateTo(url) {
            uni.navigateTo({
                url,
            })
        },

        formatDate(dateString) {
            return formatDateChinese(dateString)
        },

        formatImages(imagesStr) {
            return formatImages(imagesStr)
        },

        editWarehouseRecord(item) {
            // 编辑记录，跳转到编辑页面
            uni.navigateTo({
                url: `/pages/warehouse/warehouseIn/addWarehouseIn?id=${item.id}`,
            })
        },

        confirmDelete(item) {
            uni.showModal({
                title: '确认删除',
                content: `确定要删除这条农资入库记录吗？`,
                success: (res) => {
                    if (res.confirm) {
                        this.deleteWarehouseRecord(item.id)
                    }
                },
            })
        },

        async deleteWarehouseRecord(id) {
            try {
                uni.showLoading({ title: '删除中...' })

                // 这里应该调用真实的API
                // const res = await warehouse.deleteWarehouseInRecord(id)

                // 模拟删除成功
                const index = this.warehouseList.findIndex((item) => item.id === id)
                if (index !== -1) {
                    this.warehouseList.splice(index, 1)
                }

                uni.showToast({
                    title: '删除成功',
                    icon: 'success',
                })
            } catch (error) {
                console.error('删除农资入库记录失败:', error)
                uni.showToast({
                    title: '删除失败',
                    icon: 'none',
                })
            } finally {
                uni.hideLoading()
            }
        },

        // 加载更多数据
        async loadMoreData() {
            if (this.loadingMore || !this.hasMore) {
                return
            }

            this.pageParams.pageNo += 1
            await this.fetchWarehouseList(true)
        },
    },
}
</script>

<style lang="scss" scoped>
.search-parent {
    padding: 20rpx 30rpx;
}
.search-box1 {
    padding: 10rpx 0rpx 0;
    background-color: #fff;
}

/* 农资入库列表样式 */
.warehouse-list {
    padding: 20rpx 30rpx 100rpx;
    .title {
        font-family: OPPOSans, OPPOSans;
        font-weight: bold;
        font-size: 28rpx;
        color: #434343;
        margin: 0 0 10px 10px;
    }
}

.warehouse-item {
    background-color: #fff;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);

    &:active {
        background-color: #f8f9fa;
    }
}

.item-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24rpx;
    padding-bottom: 10rpx;
    border-bottom: 1px solid #eeeeee;
}

.header-left {
    flex: 1;
}

.item-title {
    font-family: OPPOSans, OPPOSans;
    font-weight: 500;
    font-size: 28rpx;
    color: #434343;
    margin-bottom: 12rpx;
    display: block;
}

.item-tag {
    display: inline-block;
    background-color: rgba(243, 238, 254, 1);
    padding: 6rpx 16rpx;
    border-radius: 4rpx;

    font-family: OPPOSans, OPPOSans;
    font-weight: 500;
    font-size: 24rpx;
    color: #6b31ff;
}

.item-details {
    margin-bottom: 20rpx;
}

.detail-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16rpx;

    &:last-child {
        margin-bottom: 0;
    }
}

.detail-label {
    font-family: OPPOSans, OPPOSans;
    font-weight: 400;
    font-size: 24rpx;
    color: #333333;
}

.detail-value {
    font-family: OPPOSans, OPPOSans;
    font-weight: 500;
    font-size: 24rpx;
    color: #999999;
}

.item-images {
    display: flex;
    gap: 16rpx;
    margin-top: 20rpx;
    padding-top: 20rpx;
    border-top: 1rpx solid #f0f0f0;

    image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 8rpx;
        background-color: #f5f5f5;
    }
}
</style>
